package com.wei.weblog.pre;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

import com.wei.weblog.mr.WebLogInfo;

public class WebLogParser {
	public static SimpleDateFormat df1 = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.US);
	public static SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

	public static WebLogInfo parser(String line) {
		WebLogInfo webLogInfo=new WebLogInfo();
		String[] array = line.split(" ");
		if (array.length>11) {
			boolean isValid = true;
			String remoteIp=array[0];
			String remoteUserInfo=array[1];
			String requestTime=formatDate(array[3].substring(1));
			String requestMethod=array[5];
			String requestUrl=array[6];
			String requestProtocol=array[7];
			String responseCode=array[8];
			String bodySendBytes=array[9];
			String refererUrl=array[10];
			String userAgent=array[11];
			if (array.length>12) {
				StringBuffer buffer=new StringBuffer();
				for (int i = 11; i < array.length; i++) {
					buffer.append(array[i]+" ");
				}
				userAgent=buffer.toString();
			}
			if (Integer.parseInt(responseCode)>400 || "invalidTime".equals(requestTime)) {
				isValid=false;
			}
			webLogInfo.set(isValid, remoteIp, remoteUserInfo, requestTime,requestUrl, requestMethod, 
					requestProtocol, responseCode, bodySendBytes, refererUrl, userAgent);
			
		}else{
			webLogInfo.setValid(false);
		}
		return webLogInfo;
	}
	
	private static String formatDate(String dateString) {
		try {
			return df2.format(df1.parse(dateString));
		} catch (ParseException e) {
			return "invalidTime";
		}
	}


	public static void filterUrl(WebLogInfo webLogInfo, Set<String> pages) {
		if (!pages.contains(webLogInfo.getRequestUrl())) {
			webLogInfo.setValid(false);
		}
	}

	public static void main(String[] args) {
		System.out.println(timeDiff("2013-09-18 07:10:51", "2013-09-19 07:10:51"));
	}

	public static long timeDiff(String time1,String time2){
		try {
			Date date1 = df2.parse(time1);
			Date date2 = df2.parse(time2);
			return date1.getTime()-date2.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}
	}
}
